﻿using CefSharp;
using CefSharp.WinForms;
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CEFdemo
{
    public partial class Form1 : Form
    {
        private ChromiumWebBrowser chromiumWebBrowser;

        public Form1()
        {
            InitializeComponent();
            InitializeChromium();
        }

        private void InitializeChromium()
        {
            CefSettings settings = new CefSettings();
            CefSharpSettings.WcfEnabled = true;
            CefSharpSettings.ConcurrentTaskExecution = true; 
            
            // 获取程序运行时的目录
            string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
    
            // 设置自定义的缓存路径为程序运行目录下的 Cache 文件夹
            string cachePath = Path.Combine(appDirectory, "Cache");
            if (!Directory.Exists(cachePath))
            {
                Directory.CreateDirectory(cachePath);
            }
            settings.CachePath = cachePath;
            
            Cef.Initialize(settings);

            // 创建 ChromiumWebBrowser 控件
            chromiumWebBrowser = new ChromiumWebBrowser();
            chromiumWebBrowser.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true;
            chromiumWebBrowser.JavascriptObjectRepository.Register("csf", new CSfunction(this), 
                isAsync: false, options: BindingOptions.DefaultBinder);
            chromiumWebBrowser.JavascriptObjectRepository.Register("csfa", new CSfunctionAsyn(), 
                isAsync: true, options: BindingOptions.DefaultBinder);
            
            Controls.Add(chromiumWebBrowser);
            chromiumWebBrowser.Dock = DockStyle.Fill;
            chromiumWebBrowser.LoadingStateChanged += async (sender, args) => await ChromiumWebBrowser_LoadingStateChanged(sender, args);

            // 写入嵌入资源文件到临时目录
            string tempDirectory = Path.Combine(Path.GetTempPath(), "CEFdemo");
            Directory.CreateDirectory(tempDirectory);
            
            try
            {
                Resource.WriteResourceToFile("CEFdemo.Pages.index.html",
                    Path.Combine(tempDirectory, "index.html"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.css.bootstrap.min.css",
                    Path.Combine(tempDirectory, "static/css/bootstrap.min.css"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.css.treestyles.css",
                    Path.Combine(tempDirectory, "static/css/treestyles.css"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.js.jquery.min.js",
                    Path.Combine(tempDirectory, "static/js/jquery.min.js"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.js.bootstrap.bundle.min.js",
                    Path.Combine(tempDirectory, "static/js/bootstrap.bundle.min.js"));
                Resource.WriteResourceToFile("CEFdemo.Pages.index.js", Path.Combine(tempDirectory, "index.js"));
                Resource.WriteResourceToFile("CEFdemo.Pages.index.css", Path.Combine(tempDirectory, "index.css"));

                // 写入SVG图片资源
                Resource.WriteResourceToFile("CEFdemo.Pages.static.svg.markdown-fill.svg",
                    Path.Combine(tempDirectory, "static/svg/markdown-fill.svg"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.svg.dash-lg.svg",
                    Path.Combine(tempDirectory, "static/svg/dash-lg.svg"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.svg.fullscreen-exit.svg",
                    Path.Combine(tempDirectory, "static/svg/fullscreen-exit.svg"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.svg.x-lg.svg",
                    Path.Combine(tempDirectory, "static/svg/x-lg.svg"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.svg.journal-text.svg",
                    Path.Combine(tempDirectory, "static/svg/journal-text.svg"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.svg.cloud-arrow-up.svg",
                    Path.Combine(tempDirectory, "static/svg/cloud-arrow-up.svg"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.svg.person.svg",
                    Path.Combine(tempDirectory, "static/svg/person.svg"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.svg.gear.svg",
                    Path.Combine(tempDirectory, "static/svg/gear.svg"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.svg.folder2-open.svg",
                    Path.Combine(tempDirectory, "static/svg/folder2-open.svg"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.svg.file-earmark-plus.svg",
                    Path.Combine(tempDirectory, "static/svg/file-earmark-plus.svg"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.svg.folder-plus.svg",
                    Path.Combine(tempDirectory, "static/svg/folder-plus.svg"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.svg.arrow-clockwise.svg",
                    Path.Combine(tempDirectory, "static/svg/arrow-clockwise.svg"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.svg.trash.svg",
                    Path.Combine(tempDirectory, "static/svg/trash.svg"));
                Resource.WriteResourceToFile("CEFdemo.Pages.static.svg.cloud-download.svg",
                    Path.Combine(tempDirectory, "static/svg/cloud-download.svg"));
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error writing resource to file: {ex.Message}");
            }

            // 加载本地 HTML 文件
            chromiumWebBrowser.Load(Path.Combine(tempDirectory, "index.html"));

            // 设置窗体全屏
            MaximizedBounds = Screen.PrimaryScreen.WorkingArea;
            WindowState = FormWindowState.Maximized;
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private async Task ChromiumWebBrowser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
        {
            // 页面加载完成后，可以在此处执行其他操作
            if (e.IsLoading == false)
            {
                try
                {
                    string[] message = new string[] { "0011", "getkey"};
                    string tostring = string.Join(",", message);
                    Client client = new Client();
                    byte[] data = Encoding.UTF8.GetBytes(tostring);
                    await client.stream.WriteAsync(data, 0, data.Length);
                    byte[] responseData = new byte[1024];
                    int bytesRead = await client.stream.ReadAsync(responseData, 0, responseData.Length);
                    string key = Encoding.UTF8.GetString(responseData, 0, bytesRead);
                    ClientEncryption.SetPublicKey(key);
                }
                catch (SocketException exception)
                {
                    chromiumWebBrowser.GetBrowser().MainFrame.ExecuteJavaScriptAsync("alert('服务器连接失败')");
                }
            }
        }
    }
}